package com.cssl.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.TextNode;

import java.util.Arrays;
import java.util.List;

public class SubStringUtil {

    public static List<String> subGoodsSpecifications(String needSub){
        String specifications = needSub;
        specifications = specifications.substring(1, specifications.length() - 2); /**=> 颜色','规格','信息 */
        String[] split = specifications.split("','");
        List<String> strings = Arrays.asList(split);
        return strings;
    }

    public static String giveStringsBackJson(List<String> strings){
        ObjectMapper mapper = new ObjectMapper();
        ArrayNode jsonArray = mapper.createArrayNode();
        for (String element : strings) {
            String trimmedElement = element.trim();
            // 只添加非空元素
            if (!trimmedElement.isEmpty()) {
                jsonArray.add(new TextNode(trimmedElement));
            }
        }
        String jsonOutput = "";
        // 将 JSON 数组转为字符串
        try {
            jsonOutput = mapper.writeValueAsString(jsonArray);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return jsonOutput;
    }
}
